package pl.auto.ws;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;


public class Generator {

	private final static String YES = "UPRAWNIONA";

	private final static String NOTEXIST = "NIE ISTNIEJE";

	private final static String NO = "NIE UPRAWNIONA";
	
	private final static Logger LOGGER = Logger.getLogger(Generator.class .getName()); 
	
	public String getSession() {
		String s = "";
		for (int i=0; i<32; i++){
			s+=(char) (65 + Math.random()*25);
		}
		return s;
	}
	
	public String getToken() {
		String s = "";
		for (int i=0; i<32; i++){
			s+=(char) (65 + Math.random()*25);
		}
		return s;
	}
	
	public String getDate() {
		Date d = new Date();
		return d.toString();
	}
	
	public String getFile(String file) {
		try {
			//LOGGER.info(readFile(file, Charset.defaultCharset()));
			return readFile(file, Charset.defaultCharset());
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return "";
	}

	static String readFile(String path, Charset encoding) throws IOException {
		byte[] encoded = Files.readAllBytes(Paths.get(path));
		return encoding.decode(ByteBuffer.wrap(encoded)).toString();
	}

	public String prepareCheckSoap(String pesel) {
		String soap = getFile("resources/check.xml");
		soap = soap.replace("sesja", getSession());
		soap = soap.replace("sToken", getToken());
		soap = soap.replace("data", getDate());
		soap = soap.replace("szukanyPesel", pesel );
		return soap;
	}
	
	public String prepareLoginSoap(String login, String pass) {
		String soap = getFile("resources/login.xml");
		soap = soap.replace("userLogin", login);
		soap = soap.replace("userPass", pass);
		return soap;
	}
	
	public String prepareLogoutSoap(String pesel) {
		String soap = getFile("resources/logout.xml");
		soap = soap.replace("sesja", getSession());
		soap = soap.replace("sToken", getToken());
		return soap;
	}
	
	public Map<String, String> executeLogin() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("sesja", getSession());
		map.put("token", getToken());
		return map;
	}
	
	public String executeCheck(String check) {
		if (check.equals("01010153201")) {
			return Generator.NOTEXIST;
		} 
		int i = (int) (check.charAt(10));
		if (i == 49 || i == 51 || i == 53 || i == 55 || i == 57) {
			return Generator.NO;
		}
		return Generator.YES;
	}
}
